package zozopo.background.operator;


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.apache.struts2.interceptor.SessionAware;
import org.json.JSONException;
import org.json.JSONObject;


import zozopo.background.operator.operations.OperatorOS;
import zozopo.background.operator.operations.OperatorTB;
import zozopo.background.operator.operations.OperatorlimitedOS;
import zozopo.background.operator.operations.OperatorlimitedTB;
import zozopo.background.operator.operations.QQOperatorOS;
import zozopo.background.operator.operations.QQOperatorTB;
import zozopo.comm.Validate;
import zozopo.operations.comm.DictionaryTB;


import com.octo.captcha.module.servlet.image.SimpleImageCaptchaServlet;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class BindingQQAction extends  ActionSupport implements Action ,SessionAware, ServletResponseAware,ServletRequestAware{
	private static final Log logger = LogFactory.getLog(LogFactory.class);

	private HttpServletResponse response;
	private HttpServletRequest request;
	private Map<Object, Object> session;
	
	private String redirect;
	
	private String email;
	private String operatorname;
	private String password;
	private String valicode;
	
	//传出参数
	private String access_token = "";
	private String expires_in = "";
	private String openid = "";
	private String userInfoJSONStr = "";
	private String client_id = "";
	
	private JSONObject userInfojson;
	
	StringBuffer setupStr1 = new  StringBuffer();
	StringBuffer setupStr2 = new  StringBuffer();
	StringBuffer setupStr3 = new  StringBuffer();
	
	//用户信息.
	private String ret = "";
	private String msg = "";
	private String nickname = "";
	private String figureurl = "";
	private String figureurl_1 = "";
	private String figureurl_2 = "";
	private String gender = "";
	
	public String execute() throws Exception {
		//ActionContext actionContext = ActionContext.getContext(); 

		return "success";
	}
	
	public void setServletRequest(HttpServletRequest arg0) {
		// TODO Auto-generated method stub
		request = arg0;
	}
	
	public void validate() {
		
		ActionContext actionContext = ActionContext.getContext(); 
		
		//验证码
		boolean captchaPassed = SimpleImageCaptchaServlet.validateResponse(request, valicode);
		
		if(!captchaPassed){
			addFieldError("errormessage",getText("background.login.valicode.iswrong"));
			return;
		}
		
		if(getEmail().trim().equals("")){
			addFieldError("errormessage", getText("background.login.email") + getText("background.common.isnotnull"));
			return;
		}
		
		if(email.length() > 320){
			addFieldError("errormessage","email大于320个字符,请重新输入");
			return;
		}
		
		if(! Validate.isEmail(email)){
			addFieldError("errormessage","e-mail格式错误!请输入正确的e-mail.");
			return;
		}
		
		
		try {  
			OperatorOS operatorOS = new OperatorOS();
			
			if(!operatorOS.isRealOperatorByEmail(getEmail(), getPassword())){
				//清空session valicode
				session.put("valicode", "");
				addFieldError("errormessage", getText("background.login.sign.wrong"));
				operatorOS.releaseConnection();
				return;
			}
			try {
				getQQInfo();
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			OperatorTB operator = operatorOS.getInfoByEmail(email);
			
			QQOperatorOS qqOperatorOS = new QQOperatorOS(operatorOS.getConn());
			
			
			
			QQOperatorTB qqoperator = new QQOperatorTB();
			qqoperator.setAccess_token(access_token);
			
			qqoperator.setEmail(operator.getEmail_operator());
			qqoperator.setOperatorid(operator.getId_operator());
			
			qqoperator.setFigureurl(figureurl);
			qqoperator.setFigureurl_1(figureurl_1);
			qqoperator.setFigureurl_2(figureurl_2);
			qqoperator.setGender(gender);
			qqoperator.setNickname(nickname);
			qqoperator.setOpenid(openid);
			
			
			
			if(qqOperatorOS.isExistOpenId(openid)){  //如果openid已经存在就update Access_tonken.
				qqOperatorOS.update(qqoperator);
			}else{                                   //否则加入新的 openid 
				qqOperatorOS.insert(qqoperator);
			}
			
			qqoperator = qqOperatorOS.getInfoByEmail(operator.getEmail_operator());   //得到最新的 qqooperator INFO
			
			
			OperatorlimitedOS userlimitedOS = new OperatorlimitedOS(operatorOS.getConn());
			
			Map<String,OperatorlimitedTB> operatorlimitedMap = userlimitedOS.getUserlimitedMap(operator);
			session.put("operatorInfo", operator);
			session.put("operatorlimitedMap", operatorlimitedMap);
			session.put("qqoperatorInfo", qqoperator);
			
			// 若debug模式开启，则输出debug 信息
	        if (logger.isDebugEnabled()) {
	            logger.debug(getEmail() +" "+getPassword() + " " + getValicode());
	        }
	        
			operatorOS.releaseConnection();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			addFieldError("errormessage", "系统错误请联系管理人员");
			return;
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			addFieldError("errormessage", "系统错误请联系管理人员");
			return;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			addFieldError("errormessage", "系统错误请联系管理人员");
			return;
		}
	}
	
	public String getQQInfo() throws JSONException, IOException{
		
		access_token = (String) session.get("access_token");
		openid = (String) session.get("openid");
		
		//第三步.
		String setup2 ="https://graph.qq.com/user/get_user_info?access_token="+access_token+"&oauth_consumer_key=100231532&openid="+openid;  
		//{ "ret":0, "msg":"", "nickname":"啊编先生", "figureurl":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/30", "figureurl_1":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/50", "figureurl_2":"http://qzapp.qlogo.cn/qzapp/100231532/BBCE43A56DC0F1AF2FB407518A4F1240/100", "gender":"男" } 
		
		URL url3= new URL(setup2);
		HttpURLConnection urlconn3 = (HttpURLConnection) url3.openConnection();
		urlconn3.connect();
		InputStream stream = urlconn3.getInputStream();
		BufferedReader reader = new BufferedReader(new InputStreamReader(stream,"UTF-8"));
		
		
		String temp3 ="";
		while((temp3 = reader.readLine()) != null){
			setupStr3.append(temp3+"\n");
		}
		
		urlconn3.disconnect();
		stream.close();
		reader.close();
		
		userInfojson= new JSONObject(setupStr3.toString());
		
		ret = userInfojson.get("ret").toString();
		msg = userInfojson.get("msg").toString();
		nickname = userInfojson.get("nickname").toString();
		figureurl = userInfojson.get("figureurl").toString();
		figureurl_1 = userInfojson.get("figureurl_1").toString();
		figureurl_2 = userInfojson.get("figureurl_2").toString();
		gender = userInfojson.get("gender").toString();

	
	return "";
}

	
	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	

	public String getValicode() {
		return valicode;
	}

	public void setValicode(String valicode) {
		this.valicode = valicode;
	}

	public void setSession(Map arg0) {
		// TODO Auto-generated method stub
		session = arg0;
	}
	public void setServletResponse(HttpServletResponse arg0) {
		// TODO Auto-generated method stub
		response = arg0;
	}
	
	public String getRedirect() {
		return redirect;
	}

	public void setRedirect(String redirect) {
		
		this.redirect = redirect;
	}

	public String getOperatorname() {
		return operatorname;
	}

	public void setOperatorname(String operatorname) {
		this.operatorname = operatorname;
	}

}
